<?php

class SocialController extends Buzz_AuthedController {
    private $mapper;
    private $parser;


    public function init() {
        $this->mapper = new Application_Model_CommentMapper();
        $this->parser = new Buzz_CommentParser();
    }

    protected function doPreDispatch() {
        return;
    }

    public function indexAction() {
        $actionUrl = $this->view->url(array(), "publish", true);
        $this->view->publishForm = new Application_Form_AddComment(
                array("id" => "comment_form", "action" => $actionUrl));
        $this->view->comments = $this->mapper->fetchPaginated(0);

    }

    public function groupcommentsAction() {
        $id = $this->getRequest()->getParam("id");
        $gmapper = new Application_Model_GroupMapper();
        $this->view->comments = $gmapper->findLinkedComments($id);
    }

    public function elementcommentsAction() {
        $id = $this->getRequest()->getParam("id");
        $gmapper = new Application_Model_ElementMapper();
        $this->view->comments = $gmapper->findLinkedComments($id);
    }

    public function publishAction() {
        $user = $this->view->user;
        $comment = $this->getRequest()->getParam("comment");
        $parsed = $this->parser->parse($comment);
        $insertComment = new Application_Model_Comment(null, $user->id(), null, $parsed["rewritten"]);
        $id = $this->mapper->save($insertComment);
        foreach ($parsed["groups"] as $group) {
            $this->mapper->linkGroup($id, $group->id());
        }
        foreach ($parsed["elements"] as $elem) {
            $this->mapper->linkElement($id, $elem->id());
        }

        $insertComment->set_id($id);
        $insertComment->set_user($user);
        $return = array(
                "id"    => $insertComment->id(),
                "comment" => $insertComment->content(),
                "username" => $user->login());
        $this->_helper->json($return);
    }

    public function deleteAction() {
        
    }
}